package com.ssy.lingxi.purchase.serviceimpl;

import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.purchase.api.common.OrderConstant;
import com.ssy.lingxi.purchase.api.dto.request.BaseDetailsRequest;
import com.ssy.lingxi.purchase.api.dto.request.purchase.PurchaseInquiryListRequest;
import com.ssy.lingxi.purchase.api.dto.request.purchase.PurchaseInquiryProductRequest;
import com.ssy.lingxi.purchase.api.dto.response.CountryAreaResponse;
import com.ssy.lingxi.purchase.api.dto.response.purchase.PurchaseInquiryDetailsResponse;
import com.ssy.lingxi.purchase.api.dto.response.purchase.PurchaseInquiryListResponse;
import com.ssy.lingxi.purchase.api.enums.purchase.PurchaseInquiryListEnum;
import com.ssy.lingxi.purchase.api.enums.purchase.PurchaseInquiryListExternalWorkStateEnum;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.PurchaseInquiry;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.PurchaseInquiryProduct;
import com.ssy.lingxi.purchase.repository.PurchaseInquiryProductRepository;
import com.ssy.lingxi.purchase.repository.PurchaseInquiryRepository;
import com.ssy.lingxi.purchase.service.PlatformPurchaseInquiryService;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 平台后台采购需求单业务处理
 *
 * @author wrc
 * @date 2021/1/26
 */
@Service
public class PlatformPurchaseInquiryServiceImpl extends BasePurchaseInquiry implements PlatformPurchaseInquiryService {

    @Resource
    PurchaseInquiryRepository purchaseInquiryRepository;

    @Resource
    PurchaseInquiryProductRepository purchaseInquiryProductRepository;

    /**
     * 采购询价-采购需求单查询
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> platformPurchaseInquiryList(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getPurchaseInquiryList(sysUser, request, PurchaseInquiryListEnum.PURCHASE_INQUIRY_LIST.getType());
    }

    /**
     * 采购需求单详情
     */
    @Override
    public Wrapper<PurchaseInquiryDetailsResponse> purchaseInquiryDetails(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiryDetailsResponse response = new PurchaseInquiryDetailsResponse();
        PurchaseInquiry purchaseInquiry;
        if (null != request.getId()) {
            purchaseInquiry = purchaseInquiryRepository.findById(request.getId()).orElse(null);
        } else {
            purchaseInquiry = purchaseInquiryRepository.findByPurchaseInquiryNo(request.getNumber());
        }
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(purchaseInquiry, response);
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));
        response.setAreas(purchaseInquiry.getAreas().stream().map(temp -> {
            CountryAreaResponse countryArea = new CountryAreaResponse();
            BeanUtils.copyProperties(temp, countryArea);
            return countryArea;
        }).collect(Collectors.toList()));
        //查询采购物料
        List<PurchaseInquiryProduct> products = purchaseInquiryProductRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        List<PurchaseInquiryProductRequest> productRequests = products.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            return productRequest;
        }).collect(Collectors.toList());
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        response.setMateriels(productRequests);
        //查询需求对接会员列表
        if (!OrderConstant.DockingType.PLATFORM_DOOR.equals(purchaseInquiry.getType())) {
            response.setDemandMembers(getDemandMembers(purchaseInquiry.getId()));
        }
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(purchaseInquiry.getId()));
        //查询外部流转状态
        List<Long> roles = getRolesByPurchaseInquiry(purchaseInquiry.getId());
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(),roles,purchaseInquiry.getCreateMemberRoleId()));
        return Wrapper.success(response);
    }

    /**
     * 待审核采购需求单(22.1.20版本作废)
     */
/*    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseInquiryExamineList(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getPurchaseInquiryList(sysUser, request, PurchaseInquiryListEnum.Platform_PURCHASE_INQUIRY_LIST.getType());
    }*/

    /**
     * 审核采购需求单(22.1.20版本作废)
     */
    /*@Transactional
    @Override
    public Wrapper purchaseInquiryExamine(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!PurchaseInquiryListExternalWorkStateEnum.STAY_AUDIT_REQUIREMENTS.getState().equals(purchaseInquiry.getExternalState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
        }
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), purchaseInquiry.getExternalTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        purchaseInquiry.setExternalTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setExternalState(taskResult.getData().getStatus());
        purchaseInquiry.setExternalNextStep(taskResult.getData().getStep());
        saveExternalLog(sysUser, "审核采购需求单", taskResult.getData().getStatus(), purchaseInquiry.getId(), request.getAuditOpinion());
        if (OrderConstant.State.STOP.equals(request.getState())) {
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.AFTER_SALE_REPAIR_HANDLE.getCode(), 1L, DemandPublishOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
        }
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        return Wrapper.success();
    }*/

    /**
     * 批量审核采购需求单(22.1.20版本作废)
     */
    /*@Transactional
    @Override
    public Wrapper purchaseInquiryExamineBatch(BaseDeleteAllRequest request, UserLoginCacheDTO sysUser) {
        List<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(purchaseInquirys)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (PurchaseInquiry purchaseInquiry : purchaseInquirys) {
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (!PurchaseInquiryListExternalWorkStateEnum.STAY_AUDIT_REQUIREMENTS.getState().equals(purchaseInquiry.getExternalState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_NOT_AUDIT);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), purchaseInquiry.getExternalTaskId(), OrderConstant.Auditing.PASS);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return taskResult;
            }
            purchaseInquiry.setExternalTaskId(taskResult.getData().getTaskId());
            purchaseInquiry.setExternalState(taskResult.getData().getStatus());
            purchaseInquiry.setExternalNextStep(taskResult.getData().getStep());
            saveExternalLog(sysUser, "审核采购需求单", taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
        }
        purchaseInquiryRepository.saveAll(purchaseInquirys);
        purchaseInquiryRepository.flush();
        return Wrapper.success();
    }*/

    /**
     * 平台后台-采购物料-分页查询
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryProductRequest>> purchaseInquiryProductlist(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        PurchaseInquiryProduct product = new PurchaseInquiryProduct();
        product.setPurchaseInquiryId(purchaseInquiry.getId());
        //查询采购物料
        Page<PurchaseInquiryProduct> purchaseInquiryProducts = purchaseInquiryProductRepository.findAll(Example.of(product), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        if (purchaseInquiryProducts.getTotalElements() == 0) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<PurchaseInquiryProductRequest> productRequests = purchaseInquiryProducts.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            return productRequest;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(purchaseInquiryProducts.getTotalElements(), productRequests));
    }


    /**
     * 根据不同类型查询采购询价单列表 queryType：
     */
    public Wrapper<PageData<PurchaseInquiryListResponse>> getPurchaseInquiryList(UserLoginCacheDTO sysUser, PurchaseInquiryListRequest request, Integer queryType) {
        List<PurchaseInquiryListResponse> responses = new ArrayList<>();
        Specification<PurchaseInquiry> purchaseInquiryQuery = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasLength(request.getMemberName()))
                predicates.add(criteriaBuilder.like(root.get("memberName"), "%" + request.getMemberName() + "%"));
            if (null != request.getStartTime()) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), request.getStartTime()));
            }
            if (null != request.getEndTime()) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), request.getEndTime()));
            }
            if (StringUtils.hasLength(request.getDetails())) {
                predicates.add(criteriaBuilder.like(root.get("details"), "%" + request.getDetails() + "%"));
            }
            if (StringUtils.hasLength(request.getPurchaseInquiryNo())) {
                predicates.add(criteriaBuilder.like(root.get("purchaseInquiryNo"), "%" + request.getPurchaseInquiryNo() + "%"));
            }
            if (PurchaseInquiryListEnum.PURCHASE_INQUIRY_LIST.getType().equals(queryType)) {
                if (null != request.getExternalState()) {
                    predicates.add(criteriaBuilder.equal(root.get("externalState"), request.getExternalState()));
                }
                if (null != request.getInteriorState()) {
                    predicates.add(criteriaBuilder.equal(root.get("interiorState"), request.getInteriorState()));
                }
            } /*else if (PurchaseInquiryListEnum.Platform_PURCHASE_INQUIRY_LIST.getType().equals(queryType)) { 21.1.20版本去掉
                predicates.add(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_AUDIT_REQUIREMENTS.getState()));
            }*/
            Predicate[] predicate = new Predicate[predicates.size()];
            return criteriaBuilder.and(predicates.toArray(predicate));
        };
        Page<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAll(purchaseInquiryQuery, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("createTime").descending()));
        if (0 < purchaseInquirys.getTotalElements()) {
            responses = purchaseInquirys.getContent().stream().map(temp -> {
                PurchaseInquiryListResponse response = new PurchaseInquiryListResponse();
                response.setCreateTime(temp.getCreateTime());
                response.setDeliveryTime(temp.getDeliveryTime());
                response.setPurchaseInquiryNo(temp.getPurchaseInquiryNo());
                response.setOfferEndTime(temp.getOfferEndTime());
                response.setId(temp.getId());
                response.setMemberRoleId(temp.getMemberRoleId());
                response.setMemberName(temp.getMemberName());
                response.setMemberId(temp.getMemberId());
                response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(temp.getExternalState()));
                response.setDetails(temp.getDetails());
                response.setExternalState(temp.getExternalState());
                response.setCreateTime(temp.getCreateTime());
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(purchaseInquirys.getTotalElements(), responses));
    }

}
